# coding=utf8

import pandas as pd
import numpy as np


class Preliminary:

    @staticmethod
    def astype():
        d = {'col1': [1, 2], 'col2': [3, 4]}
        df = pd.DataFrame(data=d)
        print(
            ">>> df\n"
            f"{df}\n"
            f">>> df.dtypes\n{df.dtypes}\n"
            f">>> df.astype('int32').dtypes\n"
            f"{df.astype('int32').dtypes}\n"
            ">>> df.astype({'col1': 'int32'}).dtypes\n"
            f"{df.astype({'col1': 'int32'}).dtypes}"
        )
        s1 = pd.Series([1, 2])
        s2 = s1.astype('int64', copy=False)
        print(
            "s2 = s1.astype('int64', copy=False)\n"
            f"{s2}\n"
        )
        s2[0] = 10
        print(
            ">>> s2[0] = 10\n"
            ">>> s1\n"
            f"{s1}"
            )

    @staticmethod
    def convert_dtypes():
        df = pd.DataFrame(
            data = {
            "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
            "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
            "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
            "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
            "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
            "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
            }
        )
        dfn = df.convert_dtypes()
        print(
            f">>> df\n{df}\n{df.dtypes}\n"
            f">>> dfn = df.convert_dtypes()\n"
            f">>> dfn\n{dfn}\n"
            f">>> dfn.dtypes\n{dfn.dtypes}\n"

        )

    @staticmethod
    def to_numeric():
        df = pd.DataFrame(
            [[1, "2020-01-02", "1231"], ["2020", "1998", 12]],
            columns=list('abc')
            )
        print(
            ">>> df\n"
            f"{df}\n"
            f">>> df.a.dtype, df.b.dtype, df.c.dtype\n"
            f"{df.a.dtype, df.b.dtype, df.c.dtype}\n"
            f">>> pd.to_numeric(df.a)\n"
            f"{pd.to_numeric(df.a)}\n"
            f">>> pd.to_numeric(df.b, errors='coerce')\n"
            f"{pd.to_numeric(df.b, errors='coerce')}\n"
            f">>> pd.to_numeric(df.c, errors='coerce', downcast='integer')\n"
            f"{pd.to_numeric(df.c, downcast='integer')}\n"
        )


def task(filename="stu94.csv"):
    df = pd.read_csv(filename, encoding='utf8', header=None, names=['name', 'age', 'birthday'])
    print('读出数据及类型：')
    print(df)
    print(df.dtypes)
    df2 = df.astype({"age": np.float16})
    print('使用astype转换数据结果及类型：')
    print(df2)
    print(df2.dtypes)
    df3 = df.convert_dtypes()
    print('使用convert_dtypes转换数据结果及类型：')
    print(df3)
    print(df3.dtypes)



if __name__ == "__main__":
    # Preliminary.astype()
    # Preliminary.convert_dtypes()
    task()
